import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal } from 'antd';
import { toJS } from 'mobx';
import { Condition, getAdButtons } from './list/listCondition';
import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaTools, WeaAlertPage } from 'ecCom';
// import WorkPlan from "weaWorkplan"
import * as Operate from '../util/Operate';
import BatchShareDialog from './comp/crm-batch-share';
import SearchAssignDialog from './dialog/searchAssignDialog';
import ChangeStatusDialog from './dialog/changeStatusDialog';
import { getCustomerNameById } from '../util/index';
import { locale } from 'moment';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

@inject('crmSearchStore', 'crmInfoRightmenuStore')
@observer
class Search extends React.Component {
  constructor(props) {
    super(props);
    window._crmTable = {
      reLoad: props.crmSearchStore.reLoad,
      getSelectedKeys: props.crmSearchStore.getSelectedKeys,
      setSelectedKeys: props.crmSearchStore.setSelectedKeys,
    };
    this.state = {
      visible: false,
      visibleCowork: false,
      customerId: '',
      crmArr: [],
      workplanLoaded: false,
      coworkLoaded: false,
    };
  }

  componentDidMount() {
    this.doInit(this.props);
    if (window.weaWorkplan) {
      this.setState({ workplanLoaded: true });
    } else {
      eventRegister.loadModule('f_workplan', () => {
        this.setState({ workplanLoaded: true });
      }, () => {
        // 加载文件失败 的业务处理， 网络超时，没文件之类
        alert('加载日程模块失败，请联系系统管理员！');
      });
    }

    if (window.weaCowork) {
      this.setState({ coworkLoaded: true });
    } else {
      eventRegister.loadModule('f_cowork', () => {
        this.setState({ coworkLoaded: true });
      }, () => {
        // 加载文件失败 的业务处理， 网络超时，没文件之类
        alert('加载协作模块失败，请联系系统管理员！');
      });
    }
  }
  doInit(props) {
    const { params, crmSearchStore, location } = props;
    const { initDatas, doSearch, getTitleInfo, getFormCondition } = crmSearchStore;
    getTitleInfo({ selectType: params.type, ...location.query });
    getFormCondition();
  }
  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    const paramsOld = this.props.params;
    const paramsNew = nextProps.params;
    if (keyOld !== keyNew || paramsOld !== paramsNew) {
      const { params, crmSearchStore, location } = nextProps;
      const { initDatas, doSearch, getTitleInfo } = crmSearchStore;
      crmSearchStore.clearStatus();
      getTitleInfo({ selectType: params.type, ...location.query });
      crmSearchStore.resetTable();
    }
  }
  componentWillUnmount() {
    const { crmSearchStore } = this.props;
    crmSearchStore.clearStatus();
  }
  render() {
    const { location, params } = this.props;
    const { crmSearchStore } = this.props;
    const { title, loading, tableStore, showSearchAd, form, verified, hasRight, baseParams, showModal, batchShareStore, shareCondition } = crmSearchStore;
    const formParams = form.getFormParams() || {};
    const { selectedRowKeys } = tableStore;
    const account = WeaTools.ls.getJSONObj('theme-account');
    if (verified && !hasRight) {
      return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@01imk3`} >
        <div style={{ color: '#000' }}>
          {getLabel(2012, '对不起，您暂时没有权限！')}
        </div>
      </WeaAlertPage>
      );
    }
    let WorkPlanCreate = {};
    if (window.weaWorkplan) {
      WorkPlanCreate = weaWorkplan.com.WorkPlanCreate;
    }
    if (verified && hasRight) {
      const currentCrmId = this.state.customerId;
      if (params.type == 'search' || params.type == 'share' || params.type == 'monitor' || params.type == 'assign' || params.type == 'hrmView') {
        return (
          <WeaRightMenu
            ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@r7v699`}
            datas={this.getRightMenu()}
            onClick={this.onRightMenuClick}
            collectParams={{
              favname: title,
              favouritetype: 4,
              importantlevel: 1,
              objid: -1,
            }}
          >
            <WeaTop
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@qrhwkg`}
              title={title}
              loading={loading}
              icon={<i className="icon-coms-crm" />}
              iconBgcolor="#96358a"
              buttons={this.getTopButtons()}
              buttonSpace={10}
              showDropIcon
              dropMenuDatas={this.getRightMenu()}
              onDropMenuClick={this.onRightMenuClick}
            >
              <WeaTab
                ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@8lkoyo`}
                buttonsAd={getAdButtons(crmSearchStore, this.props.ecId || '')}
                searchType={['base', 'advanced']}
                searchsBaseValue={formParams.name}
                setShowSearchAd={this.setShowSearchAd}
                hideSearchAd={this.setShowSearchAd}
                searchsAd={
                  <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@iozim7`} listStore={crmSearchStore} form={form} onEnterSearch={this.onEnterSearch} /></div>
                }
                showSearchAd={showSearchAd}
                onSearch={this.onSearch}
                onSearchChange={this.onSearchChange}
              />

              <WeaTable
                ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@q9hxqt`}
                comsWeaTableStore={tableStore}
                hasOrder
                needScroll
                onOperatesClick={this.onOperatesClick}
                selectedRowKeys={toJS(crmSearchStore.selectedRowKeys)}
                tableWidth={this.getTableWidth}
              />
            </WeaTop>
            {
              baseParams.selectType == 'assign' || baseParams.selectType == 'monitor' ?
                <SearchAssignDialog ecId={`${this && this.props && this.props.ecId || ''}_SearchAssignDialog@wpwuby`} contentStore={crmSearchStore} /> : ''
            }
            {
              baseParams.selectType == 'monitor' ?
                <ChangeStatusDialog ecId={`${this && this.props && this.props.ecId || ''}_ChangeStatusDialog@24mksd`} contentStore={crmSearchStore} /> : ''
            }
            {
              <BatchShareDialog
                ecId={`${this && this.props && this.props.ecId || ''}_BatchShareDialog@pxwk13`}
                visible={batchShareStore.visible}
                condition={toJS(shareCondition)}
                onSave={(v) => {
                  // console.log(v);
                  crmSearchStore.saveCustomerShare({ customerIds: `${toJS(selectedRowKeys)}`, info: JSON.stringify(v) });
                }
                }
                onCancel={() => { batchShareStore.handleShareDialog(false); }}
              />
            }
            {this.state.workplanLoaded && window.weaWorkplan && (
              <WorkPlanCreate
                ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@0wa01z`}
                type={'create'}// 新建为'create',查看为'preview',编辑edit,共享share
                visible={this.state.visible}// 显隐受控
                doClose={this.setWorkPlanVisisble}// 关闭回调
                onlyClose={this.setWorkPlanVisisble}// 关闭回调,只做关闭操作
                workPlanId={''} // 日程id，1查看日程时用到
                createConditionParams={[]}// 创建的默认值日期和时间,没有传[]
                activeKey={''} // 查看页面显示的面板1是基本信息，7是相关交流
                // changeTab={() => {}}// 查看页面切换面板的回调
                selectUser={account && account.userid}// 新建日程的创建人id
                workPlanTypeOptions={3}// 客户模块的新建日程，普通新建传'',客户新建传3
                crmIDs={this.state.visible && this.state.crmArr}// 通过客户模块新建日程，并自动带出相关客户,[{'id':'','name':''}]
                description={''}
              />
            )}

            {this.state.coworkLoaded && window.weaCowork && window.weaCowork.com && window.weaCowork.com.CreateCowork && this.state.visibleCowork && (
              <window.weaCowork.com.CreateCowork
                ecId={`${this && this.props && this.props.ecId || ''}_undefined@dp8mki`}
                random={Math.random()}
                initAddQuery={
                  {
                    relatedType: 'crm',
                    ids: currentCrmId,
                  }
                }
                onCancel={() => {
                  this.setState({ visibleCowork: false });
                }}
              />
            )}
          </WeaRightMenu>);
      }
      return (
        <WeaRightMenu
          ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@aj17er`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
          collectParams={{
            favname: title,
            favouritetype: 4,
            importantlevel: 1,
            objid: -1,
          }}
        >
          <div className="crm-reprot-info" >
            <WeaTab
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@p5672o`}
              buttonsAd={getAdButtons(crmSearchStore, this.props.ecId || '')}
              searchType={['base', 'advanced']}
              searchsBaseValue={formParams.name}
              setShowSearchAd={this.setShowSearchAd}
              hideSearchAd={this.setShowSearchAd}
              searchsAd={
                <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@cg4c7y`} listStore={crmSearchStore} form={form} onEnterSearch={this.onEnterSearch} /></div>
              }
              showSearchAd={showSearchAd}
              onSearch={this.onSearch}
              onSearchChange={this.onSearchChange}
              buttons={this.getTopButtons()}
            />
          </div>
          <WeaTable
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@efgag8`}
            comsWeaTableStore={tableStore}
            hasOrder
            needScroll
            onOperatesClick={this.onOperatesClick}
            tableWidth={this.getTableWidth}
          />
          {window.weaWorkplan && (
            <WorkPlanCreate
              ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@e69jik`}
              type={'create'}// 新建为'create',查看为'preview',编辑edit,共享share
              visible={this.state.visible}// 显隐受控
              doClose={this.setWorkPlanVisisble}// 关闭回调
              onlyClose={this.setWorkPlanVisisble}// 关闭回调,只做关闭操作
              workPlanId={''} // 日程id，1查看日程时用到
              createConditionParams={[]}// 创建的默认值日期和时间,没有传[]
              activeKey={''} // 查看页面显示的面板1是基本信息，7是相关交流
              changeTab={() => {}}// 查看页面切换面板的回调
              selectUser={account && account.userid}// 新建日程的创建人id
              workPlanTypeOptions={3}// 客户模块的新建日程，普通新建传'',客户新建传3
              crmIDs={this.state.visible && this.state.crmArr}// 通过客户模块新建日程，并自动带出相关客户,[{'id':'','name':''}]
              description={''}// 客户模块需求，支持新建时传入的'基本信息-内容'
            />
          )}

          {window.weaCowork && window.weaCowork.com && window.weaCowork.com.CreateCowork && this.state.visibleCowork && (
            <window.weaCowork.com.CreateCowork
              ecId={`${this && this.props && this.props.ecId || ''}_undefined@3gs2e5`}
              random={Math.random()}
              initAddQuery={
                {
                  relatedType: 'crm',
                  ids: currentCrmId,
                }
              }
            />)}
        </WeaRightMenu>
      );
    }
    return <div />;
  }

    getTableWidth = (columns) => {
      const showLength = columns.filter(col => col.display == 'true').length;
      return 120 * showLength;// 也支持返回固定值，如果小于100%,不会生效。
    }

    getTopButtons() {
      const { crmSearchStore } = this.props;
      const { rightMenu, tableStore, batchShareStore } = crmSearchStore;
      const { selectedRowKeys } = tableStore;
      const btnArr = [];
      const that = this;
      const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
      rightMenu && rightMenu.length > 0 && toJS(rightMenu).map((m) => {
        m.isTop == '1' && btnArr.length < 4 && btnArr.push(
          <Button
            ecId={`${this && this.props && this.props.ecId || ''}_Button@nq3l9b@${m.type}`}
            type="primary"
            disabled={isDisabled && m.isControl == '1'}
            onClick={() => {
              let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
              if (fn == '') {
                if (m.type == 'BTN_EXPORT') { // 导出Excel
                  //    crmSearchStore.crmExport();
                } else if (m.type == 'BTN_SHAREBATCH') { // 批量共享
                  batchShareStore.handleShareDialog(true);
                } else if (m.type == 'BTN_CHANGEMANAGER') { // 修改客户经理
                  crmSearchStore.showCustomerModal(true, `${toJS(selectedRowKeys)}`, 'monitor');
                } else if (m.type == 'BTN_ASSIGN') { // 分配客户经理
                  crmSearchStore.showCustomerModal(true, `${toJS(selectedRowKeys)}`, 'assign');
                }
              } else {
                fn = Operate.fnJoinPara(fn);
                if (selectedRowKeys) {
                  let ids = '';
                  toJS(selectedRowKeys).map((id) => {
                    ids += `,${id}`;
                  });
                  ids = ids.length > 0 ? ids.substring(1) : ids;
                  fn = Operate.fnJoinPara(fn, ids);
                }

                eval(`Operate.${fn}`);
              }
            }}
          >
            {m.menuName}
          </Button>,
        );
      });
      return btnArr;
    }

    getRightMenu() {
      const { crmSearchStore } = this.props;
      const { rightMenu, tableStore } = crmSearchStore;
      const btnArr = [];
      const { selectedRowKeys } = tableStore;
      const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
      rightMenu && rightMenu.length > 0 && rightMenu.map((m) => {
        btnArr.push({
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
          disabled: isDisabled && m.isControl == '1',
        });
      });
    	return btnArr;
    }
    onRightMenuClick=(key) => {
      const { crmSearchStore, location } = this.props;
      // console.log(location)
      const { rightMenu, tableStore, batchShareStore } = crmSearchStore;
      const { selectedRowKeys } = tableStore;
      const that = this;
      rightMenu && rightMenu.length > 0 && rightMenu.map((m, i) => {
        	if (Number(key) == i) {
          let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
        		if (fn == '') {
            if (m.type == 'BTN_COLUMN') { // 定制列
              crmSearchStore.onShowColumn();
            } else if (m.type == 'BTN_SEARCH') { // 搜索
              crmSearchStore.doSearch(location.query);
            } else if (m.type == 'BTN_SHAREBATCH') { // 批量共享
              batchShareStore.handleShareDialog(true);
            } else if (m.type == 'BTN_CHANGEMANAGER') { // 修改客户经理
              crmSearchStore.showCustomerModal(true, `${toJS(selectedRowKeys)}`, 'monitor');
            } else if (m.type == 'BTN_ASSIGN') { // 分配客户经理
              crmSearchStore.showCustomerModal(true, `${toJS(selectedRowKeys)}`, 'assign');
            } else if (m.type == 'BTN_STATUS_CHANGE') { // 客户状态变更
              crmSearchStore.showCustomerStatusModal(true, `${toJS(selectedRowKeys)}`, 'monitor');
            }
          } else {
            fn = Operate.fnJoinPara(fn);
	        		if (selectedRowKeys) {
	        			let ids = '';
	        			toJS(selectedRowKeys).map((id) => {
	        				ids += `,${id}`;
	        			});
	        			ids = ids.length > 0 ? ids.substring(1) : ids;
	        			fn = Operate.fnJoinPara(fn, ids);
	        		}
	        		eval(`Operate.${fn}`);
          }
        }
      });
    }
    onOperatesClick=(record, index, operate, flag) => {
      const { crmSearchStore, crmInfoRightmenuStore } = this.props;
      const _href = operate && operate.href ? operate.href : '';
      const fn = _href.replace('javascript:', '');
      if (flag == '0') { // 新建邮件
        // if(fn != ""){
        //     fn = Operate.fnJoinPara(fn,record.email);
        // }
        // eval("Operate." + fn);
        crmInfoRightmenuStore.addMailMenu(record.randomFieldId);
      }
      if (flag == '1') { // 新建流程
        // if(fn != ""){
        //     fn = Operate.fnJoinPara(fn,record.randomFieldId);
        // }
        // eval("Operate." + fn);
        crmInfoRightmenuStore.addWorkflow(record.randomFieldId);
      }
      if (flag == '2') { // 新建协作
        const coworkStoreMap = window.weaCowork.store && window.weaCowork.store.coworkStoreMap;
        const cowortore = coworkStoreMap && coworkStoreMap.getMapStore(3);
        this.setState({ customerId: record.randomFieldId, visibleCowork: true });
        cowortore && cowortore.setCreateState({ showNewCowork: true, createOrEdit: 0 });
      }
      if (flag == '3') { // 新建日程
        // this.setWorkPlanVisisble(true,record.randomFieldId);
        this.getCustomerInfo(record.randomFieldId);
      }
    }
    getCustomerInfo=(customerId) => {
      const crmArr = [];
      WeaTools.callApi('/api/crm/customer/getCrmNamesById', 'GET', { customerIds: customerId }).then((data) => {
        if (data.status == 'success') {
          crmArr.push({ id: customerId, name: data.datas });
          this.setState({ visible: true, crmArr });
        }
      });
      // return crmArr;
    }
    setWorkPlanVisisble=(bool = false) => {
      this.setState({ visible: bool });
    }

    setShowSearchAd=(bl) => {
      const { crmSearchStore } = this.props;
      crmSearchStore.setShowSearchAd(bl);
    }

    onSearchChange=(v) => {
      const { location, params, crmSearchStore } = this.props;
      if (crmSearchStore.form.has('name')) {
        crmSearchStore.appendFormFields({ name: { value: v } });
      } else {
        crmSearchStore.form.add(v, { key: 'name' });
      }
    }

    onSearch=(v) => {
      const { location, crmSearchStore } = this.props;
      crmSearchStore.doSearch(location.query);
      crmSearchStore.setShowSearchAd(false);
    }

    onEnterSearch=() => {
      const { crmSearchStore } = this.props;
      crmSearchStore.doSearch();
      crmSearchStore.setShowSearchAd(false);
    }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@ipqoe6`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(Search);


// WEBPACK FOOTER //
// ../src4js/pc4mobx/crm/components/Search.js
